#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int MyStrlen(const char *s)//const保护原字符串的安全
{
    int count = 0;
    while(*s != '\0')
    {
        s++;
        count++;
    }
    return count;
}

void *MyStrcpy(char *dest, const char *src)
{

    while(*src != '\0')
    {
        *dest++ = *src++;
    }
    *dest = '\0';
}

void *MyStrcat(char *dest, const char *src)
{
    while(*dest != '\0')
    {
        dest++;
    }
    MyStrcpy(dest,src);
}

// brute-force:暴力匹配算法

char *MyStrstr(const char *s, const char *d)
{
    for(int i = 0; s[i] != '\0'; i++)
    {
        int flag = 0;
        for(int j = 0; d[j] != '\0'; j++)
        {
            //没匹配上
            if(s[i + j] != d[j])
            {
                flag = 1;
                break;
            }
            if(flag == 0)
            {
                return (char*)(s + i);
            }
        }
    }
    return NULL;
}


// KMP算法


char *MyStrtok(char *dest, const char *demil)
{
    static char * next = NULL;
    if(dest != NULL)
    {
        //找到要切割字符串的首地址
        char *target = MyStrstr(dest,demil);
        if(target == NULL)
        return dest;
            
        *target = '\0';
        next = target + MyStrlen(demil);
        return dest;
    }
    else
    {
        if(next == NULL)
        {
            return NULL;
        }
        else
        {
            //没找到要切割字符
            char *target = MyStrstr(next,demil);
            if(target == NULL)
            {
                char *returnValue = next;
                next = NULL;
                return returnValue;
            }
            *target = '\0';
            char * returnValue = next;
            next = target + MyStrlen(demil);
            if(*next == '\0')
            {
                next = NULL;
            }
            return returnValue;
        }
    }
}

int MyStrcmp(const char *s1, const char *s2)
{
    while(*s1 != '\0' && *s2 != '\0')
    {
        if(*s1 != *s2)
        {
            return *s1 - *s2;
        }
        s1++;
        s2++;
    }
    return *s1 - *s2;
}

int main()
{
    char s[] = "ello";
    char s2[20] = "helloworld";
    char s3[] = "zhangsan,lisi,wangwu";
    char *p1 = "a";
    char *p2 = "a";
    //printf("%d\n",MyStrlen(s));
    //MyStrcpy(s2,s);
    //MyStrcat(s2,s);
    //char *p = MyStrstr(s2,s);
    //printf("%x %x %s\n",s2,p,p);

    //char *p = MyStrtok(s3,",");
    // while(p != NULL)
    // {
    //     printf("%s\n",p);
    //     p = MyStrtok(NULL,",");
    // }
    //printf("%s\n",p);
    //printf("%d\n",MyStrcmp(p1,p2));
    return 0;
}